/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，工作日查询功能可用');
}, false);

// 日期类型映射
const dateTypeMap = {
    1: { name: '工作日', class: 'workday' },
    2: { name: '双休日', class: 'weekend' },
    3: { name: '节假日', class: 'holiday' },
    4: { name: '补班', class: 'buban' }
};

// 表单提交处理
document.getElementById('workday-form').addEventListener('submit', function(e) {
    e.preventDefault();
    queryWorkday();
});

// 查询工作日
function queryWorkday() {
    const submitBtn = document.getElementById('submit-btn');
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const resultContainer = document.getElementById('result-container');
    
    // 获取表单数据
    const formData = {
        token: document.getElementById('token').value.trim(),
        start: document.getElementById('start').value,
        end: document.getElementById('end').value,
        need: document.getElementById('need').checked ? 1 : 0
    };
    
    // 验证token
    if (!formData.token) {
        showError('请输入API Token');
        return;
    }
    
    // 验证开始日期
    if (!formData.start) {
        showError('请选择开始日期');
        return;
    }
    
    // 验证日期范围
    if (formData.end && formData.end < formData.start) {
        showError('结束日期不能早于开始日期');
        return;
    }
    
    // 显示加载状态
    submitBtn.disabled = true;
    submitBtn.textContent = '查询中...';
    loading.classList.add('show');
    errorMessage.classList.remove('show');
    resultContainer.classList.remove('show');
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('token', formData.token);
    params.append('start', formData.start);
    if (formData.end) {
        params.append('end', formData.end);
    }
    params.append('need', formData.need);
    
    // 发送POST请求
    fetch('https://v3.alapi.cn/api/holiday/workday', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('API响应:', data);
        
        if (data.success && data.code === 200) {
            displayWorkdayResult(data.data);
        } else {
            showError(data.message || '查询失败，请检查参数');
        }
    })
    .catch(error => {
        console.error('请求错误:', error);
        showError('请求失败: ' + error.message + '。请检查网络连接或API Token是否正确');
    })
    .finally(() => {
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = '查询';
        loading.classList.remove('show');
    });
}

// 显示错误信息
function showError(message) {
    const errorMessage = document.getElementById('error-message');
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
}

// 显示查询结果
function displayWorkdayResult(data) {
    const resultContainer = document.getElementById('result-container');
    const statsGrid = document.getElementById('stats-grid');
    const datesList = document.getElementById('dates-list');
    const datesGrid = document.getElementById('dates-grid');
    
    // 显示统计信息
    statsGrid.innerHTML = `
        <div class="stat-card total">
            <div class="stat-value">${data.total || 0}</div>
            <div class="stat-label">总天数</div>
        </div>
        <div class="stat-card workday">
            <div class="stat-value">${data.workday || 0}</div>
            <div class="stat-label">工作日</div>
        </div>
        <div class="stat-card weekend">
            <div class="stat-value">${data.weekend || 0}</div>
            <div class="stat-label">周末</div>
        </div>
        <div class="stat-card holiday">
            <div class="stat-value">${data.holiday || 0}</div>
            <div class="stat-label">节假日</div>
        </div>
        <div class="stat-card buban">
            <div class="stat-value">${data.buban || 0}</div>
            <div class="stat-label">补班</div>
        </div>
    `;
    
    // 显示详细日期列表（如果有）
    if (data.dates && data.dates.length > 0) {
        datesGrid.innerHTML = '';
        data.dates.forEach(dateItem => {
            const dateType = dateTypeMap[dateItem.type] || { name: '未知', class: '' };
            const dateElement = document.createElement('div');
            dateElement.className = `date-item ${dateType.class}`;
            dateElement.innerHTML = `
                <div class="date-text">${formatDate(dateItem.date)}</div>
                <div class="date-type">${dateType.name}</div>
            `;
            datesGrid.appendChild(dateElement);
        });
        datesList.style.display = 'block';
    } else {
        datesList.style.display = 'none';
    }
    
    // 显示结果容器
    resultContainer.classList.add('show');
    
    // 滚动到结果区域
    resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// 格式化日期显示（将 YYYY-MM-DD 转换为更友好的格式）
function formatDate(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString + 'T00:00:00');
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    // 返回 MM-DD 格式
    return `${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 尝试从本地存储加载token
    const savedToken = localStorage.getItem('workday_api_token');
    if (savedToken) {
        document.getElementById('token').value = savedToken;
    }
    
    // 保存token到本地存储
    document.getElementById('token').addEventListener('blur', function() {
        const token = this.value.trim();
        if (token) {
            localStorage.setItem('workday_api_token', token);
        }
    });
    
    console.log('工作日查询页面加载完成');
});

